import stackElimination.EliminationBackoffStack;

public class TestStack {
    
    static int threadNumber = 4; //  threadNumber >= 2
    static int testTimes = 1000; // the size of the benchData
    static int benchTimes = 10;


    public static void main(String[] args) {
        int benchData[][] = new int[threadNumber][testTimes];
        EliminationBackoffStack stack = new EliminationBackoffStack<Integer>(10, 5);
        genTestData(benchData);

        runTest(stack, benchData);


    }


    public static double runTest(EliminationBackoffStack<Integer> stack, int benchData[][]) {
        SingleThreadActionOnStack[] threads = new SingleThreadActionOnStack[threadNumber];
        for (int i = 0; i < threads.length; i++) {
            threads[i] = new SingleThreadActionOnStack(stack, benchData[i]);
        }
        
        long startTime = System.nanoTime();
        try {
            for (int i = 0; i < threads.length; i++) {
                threads[i].start();
            }

            for (int i = 0; i < threads.length; i++) {
                threads[i].join();
            }
        } catch (Exception e) {
            System.out.println("Exception" + e.getMessage());
        }
        long endTime = System.nanoTime();
        double costTime = (double)(endTime - startTime);
        costTime = costTime / 1000000.0;
        System.out.printf(costTime + ",\n");    
        return costTime;
    }

    public static void genTestData(int benchData[][]) {
        // 一半的线程在入队
        // 一半的线程在出队
        for (int i = 0; i < benchData.length; i++) {
            for (int j = 0; j < benchData[i].length; j++) {
                benchData[i][j] = (i+1) % 2;
            }
        }
    }

}

class SingleThreadActionOnStack extends Thread{
    EliminationBackoffStack stack;
    int benchData[];

    SingleThreadActionOnStack(EliminationBackoffStack _stack, int _benchData[]) {
        stack = _stack;
        benchData = _benchData;
    }

    public void run() {
        for (int i = 0; i < benchData.length; i++) {
            if (benchData[i] == 1) {
                stack.push(1);
            } else {
                try {
                    stack.pop();
                } catch (Exception e){};
                
            }
        }
    }

}
